package com.emergency.direct.service.impl;

import com.emergency.direct.dao.PlanDao;
import com.emergency.direct.dao.PlanDetailDao;
import com.emergency.direct.service.PlanService;
import com.emergency.base.domain.Plan;
import com.emergency.base.domain.PlanDetail;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PlanServiceImpl implements PlanService {

    @Autowired
    private PlanDao planDao;

    @Autowired
    private PlanDetailDao planDetailDao;

    @Autowired
    private IdWorker idWorker;

    @Override
    @Transactional
    public Long protocolPlan(Plan plan) {
        if(CommonUtils.isNullOrEmpty(plan.getId())){
            plan.setId(idWorker.nextId());
        }
        planDao.save(plan);
        //保存计划明细
        planDetailSave(plan);

        return plan.getId();
    }


    private void planDetailSave(Plan plan) {
        //先删除之前的计划文件
        planDetailDao.deleteByPlanId(plan.getId());

        List<PlanDetail> planDetails=plan.getPlanDetails();
        if(!CommonUtils.isNullOrEmpty(planDetails)){
            planDetails.forEach(planDetail->{
                planDetail.setId(idWorker.nextId());
                planDetail.setPlan(plan);
            });
            planDetailDao.saveAll(planDetails);
        }
    }

    @Override
    public Plan getPlanInfo(Long planId) {
       if(CommonUtils.isNullOrEmpty(planId)){
           return null;
       }

        Plan plan=planDao.findById(planId).orElse(null);
        if(!CommonUtils.isNullOrEmpty(plan)){
            plan.setPlanDetails(planDetailDao.findAllByPlan(planId));
        }
        return plan;
    }

}
